package com.atguigu.sparkstreaming.getoffsets

import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010._
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * Created by Smexy on 2022/8/22
 *

 *    在transform中获取偏移量
 *
 *
 */
object GetOffsetsDemo1 {

  def main(args: Array[String]): Unit = {


    val streamingContext = new StreamingContext("local[*]", "wordcount", Seconds(5))

    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "hadoop102:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "sz220409test",
      "auto.offset.reset" -> "latest",
      "enable.auto.commit" -> "true"
    )


    val topics = Array("topicD")


    val ds: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
      streamingContext,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )

    ds.transform(rdd => {

      /*
          当前批次所消费到数据的偏移量信息
              OffsetRange： 代表主题中一个分区的offset信息
              所消费的主题有几个分区，就会有几个OffsetRange，把这些OffsetRange封装为集合  Array[OffsetRange]
       */
      val ranges: Array[OffsetRange] = rdd.asInstanceOf[HasOffsetRanges].offsetRanges

      for (offsetRange <- ranges) {
        println("当前消费了:"+offsetRange.topic +"  主题的" + offsetRange.partition + "  分区，从"
          + offsetRange.fromOffset + " 消费到了 " + offsetRange.untilOffset)
      }

      rdd.map(record => record.value())

    }).print(1000)

    streamingContext.start()

    streamingContext.awaitTermination()

  }

}
